package com.sinodata.bsm.cicp.finder.sqlserver;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.DBConnectionUtil;

/**
 * 
 * <p>
 * Description: SQL Server数据库发现程序
 * 程序返回：数据库名，所有者，创建时间，状态
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-14 下午05:49:37          wangpeng        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class Database extends Finder {

    private static final Logger logger = Logger.getLogger(Database.class);

    private String formatDate(String strdate, String format) {
        StringTokenizer st = new StringTokenizer(strdate, " ");
        int i = 0;
        int[] dateItem = new int[3];
        while (st.hasMoreElements()) {
            if (i == 3)
                break;
            dateItem[i] = Integer.parseInt(st.nextElement().toString());
            i++;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(dateItem[2], dateItem[0] - 1, dateItem[1]);
        SimpleDateFormat fmt = new SimpleDateFormat(format);
        return fmt.format(calendar.getTime());
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String serverName = (String) params.get("SERVERNAME");
        CallableStatement statement = null;
        ResultSet rst = null;
        Connection conn = null;
        try {
            conn = DBConnectionUtil.getInstance().getConnection("sqlserver", ip, serverName);
            if (conn != null) {
                statement = conn.prepareCall("master.dbo.sp_helpdb");
                statement.execute();
                rst = statement.getResultSet();
                while (rst.next()) {
                    String dbName = rst.getString("name").trim();
                    String[] databaseInfo = new String[7];
                    list.add(databaseInfo);
                    databaseInfo[0] = serverName + "_" + dbName;
                    databaseInfo[1] = dbName;
                    databaseInfo[2] = dbName + " in " + serverName;
                    databaseInfo[3] = rst.getString("name").trim(); //实例名
                    databaseInfo[4] = rst.getString("owner"); //所有者
                    databaseInfo[5] = formatDate(rst.getString("created"), "yyyy-MM-dd"); //创建时间
                    databaseInfo[6] = rst.getString("status"); //状态
                }
                return list;
            } else {
                return null;
            }
        } catch (Exception ex) {
            logger.error("failed to find sqlserver database", ex);
            return null;
        } finally {
            if (rst != null) {
                try {
                    rst.close();
                } catch (SQLException ex) {
                    logger.error("failed to close rst", ex);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    logger.error("failed to close statement", ex);
                }
            }
            DBConnectionUtil.getInstance().returnConnection(conn);
        }
    }
}
